﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MVCAddressBook.Models;

using MVCAddressBook.Models.Models;
using MVCAddressBook.Models.Interfaces;
using MVCAddressBook.Models.Entities;

namespace MVCAddressBook.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {
        public IFormsAuthentication FormsAuth { get; set; }
        public IAdminService AdminService { get; set; }

        public AccountController() : this(null, null) { }

        public AccountController(IFormsAuthentication formsAuth, IAdminService service)
        {
            FormsAuth = formsAuth ?? new MVCAddressBook.Models.Models.FormsAuthenticationService();
            AdminService = service ?? new MVCAddressBook.Models.Models.AdminService();
        }
        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl)
        {
            if (ValidateLogOn(userName, password))
            {
                if (AdminService.IsLogin(userName, password))
                {
                    FormsAuth.SignIn(userName, false);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    TempData["message"] = "用户名或密码错误";
                    return View();
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View();
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsAuth.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
           return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(string Name, string Password)
        {
            if (ValidateRegistration(Name, Password))
            {
                // 尝试注册用户
                AdminInfo user = new AdminInfo { Name = Name, Password = Password, LastActiveIP = Request.UserHostAddress.ToString(), IsLock = 0, RegIP = Request.UserHostAddress.ToString(), RegTime = DateTime.Now };
                if (!AdminService.IsExistUser(Name))
                {
                    if (AdminService.RegUser(user))
                    {
                        FormsAuth.SignIn(Name, false);
                        TempData["message"] = "恭喜，注册成功";
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("_FORM", "注册失败！");
                    }
                }
                else
                {
                    ModelState.AddModelError("_FORM", "该姓名已经被注册！");
                }
               
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
           
            return View();
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
          
            return View();
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(string oldPassword, string newPassword, string confirmPassword)
        {
            if (!ValidateChangePassword(oldPassword, newPassword, confirmPassword))
            {
                return View();
            }
            else
            {
                try
                {
                    if (AdminService.ChangePassword(User.Identity.Name, oldPassword, newPassword))
                    {
                        ModelState.AddModelError("_FORM", "密码修改成功.");
                        return View();
                    }
                    else
                    {
                        ModelState.AddModelError("_FORM", "您输入的新密码出错.");
                        return View();
                    }
                }
                catch (Exception)
                {
                    ModelState.AddModelError("_FORM", "您输入的密码出错或新密码非法.");
                    return View();
                }
            }
                     
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        private bool ValidateLogOn(string Name, string Password)
        {
            if (String.IsNullOrEmpty(Name))
            {
                ModelState.AddModelError("Name", "请输入用户名.");
            }
            if (String.IsNullOrEmpty(Password))
            {
                ModelState.AddModelError("Password", "请输入密码.");
            }

            return ModelState.IsValid;
        }

        private bool ValidateRegistration(string UserName, string Password)
        {
            if (String.IsNullOrEmpty(UserName))
            {
                ModelState.AddModelError("UserName", "请输入姓名.");
            }
            if (String.IsNullOrEmpty(Password))
            {
                ModelState.AddModelError("Password", "请输入密码.");
            }

            return ModelState.IsValid;
        }

        private bool ValidateChangePassword(string oldPassword, string newPassword, string confirmPassword)
        {
            if (String.IsNullOrEmpty(oldPassword))
            {
                ModelState.AddModelError("oldPassword", "请输入旧密码.");
            }
            if (String.IsNullOrEmpty(newPassword))
            {
                ModelState.AddModelError("newPassword", "请输入新密码.");
            }

            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", "两次密码输入不一致.");
            }

            return ModelState.IsValid;
        }
    }
}
